﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Shared;
using System.ServiceModel;
using RastinArgham.Robots.Activation.RobotWCF;
using Mani.Common;

namespace RastinArgham.Robots.Activation
{
    public partial class Browser : Form
    {

        System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();

        public Activate data { get; set; }
        public int interval { get; set; }
        public string url { get; set; }
        public string username { get; set; }
        public string password { get; set; }
        public bool debug { get; set; }
        public string special_username { get; set; }
        public string special_password { get; set; }

        public Browser()
        {
            timer.Enabled = false;
            timer.Tick += new EventHandler(timer_Tick);

            InitializeComponent();
        }

        void timer_Tick(object sender, EventArgs e)
        {
            timer.Stop();

            PrintHeader();

            try
            {
                switch (data.State)
                {
                    case ActivateState.Started:
                        Starting();
                        break;
                    case ActivateState.Login:
                        Login();
                        break;


                    case ActivateState.Navigate:
                        Navigate();
                        break;
                    case ActivateState.Search:
                        Search();
                        break;
                    case ActivateState.Submit:
                        Submit();
                        break;
                    case ActivateState.WaitForSubmit:
                        WaitForSubmit();
                        break;


                    case ActivateState.NavigateFinalizeActivation:
                        NavigateFinalizeActivation();
                        break;
                    case ActivateState.SearchFinalizeActivation:
                        SearchFinalizeActivation();
                        break;
                    case ActivateState.SubmitFinalizeActivation:
                        SubmitFinalizeActivation();
                        break;
                    case ActivateState.CheckFinalizeMessage:
                        CheckFinalizeMessage();
                        break;

                    case ActivateState.Success:
                        Success();
                        break;
                    default:
                        break;
                }

                PrintHeader();

                timer.Start();
            }
            catch (RobotException x)
            {
                timer.Stop();
                timer.Dispose();
                Log(x.RobotMessage);
                CRMRobotWCFClient wcfClient = new CRMRobotWCFClient();
                wcfClient.UsernameActivationReport(data.OrderId, data.Identity, false, x.RobotMessage);
                webBrowser.Dispose();
                Application.Exit();
            }
            catch (Exception ex)
            {
                timer.Stop();
                timer.Dispose();
                Log(ex.Message);
                String ErrorMessage = ex.ToString();
                try
                {
                    HtmlDocument doc = webBrowser.Document;
                    HtmlElement messageLabel = doc.GetElementById("ctl00_ContentPlaceHolder1_messageLbSearch");
                    HtmlElement loginMessageLabel = doc.GetElementById("ctl00_ContentPlaceHolder1_Login1_LabelState");

                    if (messageLabel != null)
                        ErrorMessage = messageLabel.InnerText;
                    else if (loginMessageLabel != null)
                        ErrorMessage = loginMessageLabel.InnerText;
                }
                catch
                {
                }
                CRMRobotWCFClient wcfClient = new CRMRobotWCFClient();
                wcfClient.UsernameActivationReport(data.OrderId, data.Identity, false, ErrorMessage);
                webBrowser.Dispose();
                Application.Exit();
            }
        }

        private void CheckFinalizeMessage()
        {
            HtmlDocument doc = webBrowser.Document;
            HtmlElement resultMessage = doc.GetElementById("ctl00_ContentPlaceHolder1_MessageLbl");

            if (resultMessage.InnerText != "نصب با موفقیت انجام شد و منتظر دریافت وصولی می باشد.")
                throw new RobotException(resultMessage.InnerText);
            
            data.State = ActivateState.Success;
        }

        private void WaitForSubmit()
        {
            HtmlDocument doc = webBrowser.Document;
            HtmlElement resultMessage = doc.GetElementById("ctl00_ContentPlaceHolder1_MessageLbl");

            if (resultMessage == null)
                throw new RobotException("پیام پاسخی از سامانه مبین دریافت نشد");
            if (resultMessage.InnerText.Contains("فعال شد.") || resultMessage.InnerText == "شناسه اشتراک موردنظر قبلا فعالسازی شده است" || resultMessage.InnerText.Contains("شناسه اشتراک وارد شده در حال حاضر فعال می باشد و امکان فعال سازی مجدد نمی باشد."))
                data.State = ActivateState.Success;
            else if (resultMessage != null && !String.IsNullOrEmpty(resultMessage.InnerText))
                throw new RobotException(resultMessage.InnerText);
        }

        private void SubmitFinalizeActivation()
        {
            HtmlDocument doc = webBrowser.Document;

            HtmlElement operatorText = doc.GetElementById("ctl00$ContentPlaceHolder1$InstallerNameTxt");
            HtmlElement operatorId = doc.GetElementById("ctl00$ContentPlaceHolder1$InstallerCodeTxt");
            HtmlElement installationDate = doc.GetElementById("ctl00$ContentPlaceHolder1$InstalationDateTxt$Txt_Dt");

            operatorText.InnerText = "راستین ارقام";
            operatorId.InnerText = "189211030";
            installationDate.InnerText = DateTime.Now.ToJalali();

            HtmlElement btnSubmit = doc.GetElementById("ctl00_ContentPlaceHolder1_Registerbtn");

            if (btnSubmit.GetAttribute("disabled") == "True")
            {
                throw new RobotException("دکمه تکمیل ثبت نام غیرفعال می باشد");
            }
            else
            {
                Log("Didn't go to disabled method!");
                btnSubmit.InvokeMember("click");
                data.State = ActivateState.CheckFinalizeMessage;
            }
        }

        private void SearchFinalizeActivation()
        {
            HtmlDocument doc = webBrowser.Document;

            HtmlElement searchText = doc.GetElementById("ctl00$ContentPlaceHolder1$searchSubscriberTxt");
            searchText.InnerText = data.Identity;

            HtmlElement searchBtn = doc.GetElementById("ctl00$ContentPlaceHolder1$SearchBtn");
            searchBtn.InvokeMember("click");

            data.State = ActivateState.SubmitFinalizeActivation;
        }

        private void NavigateFinalizeActivation()
        {
            webBrowser.Navigate("http://192.168.251.2/WimaxRegistrationComplete_New.aspx");
            data.State = ActivateState.SearchFinalizeActivation;
        }

        private void Navigate()
        {
            webBrowser.Navigate("http://192.168.251.2/PrepaidActivation.aspx");
            data.State = ActivateState.Search;
        }

        private void Success()
        {
            Log("Success");

            CRMRobotWCFClient wcfClient = new CRMRobotWCFClient();
            wcfClient.UsernameActivationReport(data.OrderId, data.Identity, true, null);

            Application.Exit();
        }

        private void Submit()
        {
            HtmlDocument doc = webBrowser.Document;

            HtmlElement submitBtn = null;

            submitBtn = doc.GetElementById("ctl00$ContentPlaceHolder1$OKBtn");
            

            submitBtn.InvokeMember("click");

            data.State = ActivateState.WaitForSubmit;
        }

        private void Search()
        {            
            HtmlDocument doc = webBrowser.Document;

            HtmlElement searchText = doc.GetElementById("ctl00$ContentPlaceHolder1$sub_id");
            HtmlElement searchBtn = doc.GetElementById("ctl00$ContentPlaceHolder1$searchBtn");


            searchText.InnerText = data.Identity;          

            searchBtn.InvokeMember("click");

            data.State = ActivateState.Submit;
        }

        private void Login()
        {
            HtmlDocument doc = webBrowser.Document;

            HtmlElement searchText = doc.GetElementById("ctl00$ContentPlaceHolder1$Login1$userNameTxt");
            HtmlElement passwordText = doc.GetElementById("ctl00$ContentPlaceHolder1$Login1$passwordTxt");

            if (SpecialModems.Instance.usernames.Contains(data.Identity))
            {
                searchText.InnerText = special_username;
                passwordText.InnerText = special_password;
            }
            else
            {
                searchText.InnerText = username;
                passwordText.InnerText = password;
            }

            HtmlElement loginBtn = doc.GetElementById("ctl00$ContentPlaceHolder1$Login1$loginLinkBtn");
            loginBtn.InvokeMember("click");

            if (data.OrderStateId == 100)
                data.State = ActivateState.Navigate;
            else if (data.OrderStateId == 104)
                data.State = ActivateState.NavigateFinalizeActivation;
        }

        private void Starting()
        {
            webBrowser.Navigate(url);

            data.State = ActivateState.Login;
        }

        private void PrintHeader()
        {
            txtReport.Text = data.ToString();
        }

        internal void Log(string message)
        {
            try
            {
                object callback = new object();

                string endpoint = "net.pipe://localhost/Activation/ReportService";

                ChannelFactory<IReportService> pipeFactory =
                   new ChannelFactory<IReportService>(
                      new NetNamedPipeBinding(),
                      new EndpointAddress(endpoint));

                IReportService service = pipeFactory.CreateChannel();

                service.ReportActivation(data, message);
            }
            catch (Exception)
            {

            }
            finally
            {
                //Application.Exit();
            }
        }

        internal void Start()
        {
            timer.Stop();

            data.State = ActivateState.Started;

            timer.Interval = interval * 1000;
            timer.Start();
        }

        private void webBrowser_NewWindow(object sender, CancelEventArgs e)
        {
            e.Cancel = true;
        }
    }
}
